package com.whty.cms.filewps.common.service.impl;

import com.whty.cms.filewps.common.constants.Consts;
import com.whty.cms.filewps.common.model.EsAttachment;
import com.whty.cms.filewps.common.service.CmqService;
import com.whty.cms.filewps.common.service.ICosService;
import com.whty.cms.filewps.upload.dao.AttachFileMapper;
import com.whty.cms.filewps.upload.dao.TransformJobMapper;
import com.whty.cms.filewps.upload.dto.AttachFile;
import com.whty.cms.filewps.upload.dto.TransformJob;
import com.whty.cms.filewps.upload.service.IUploadService;
import com.whty.cms.filewps.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.util.UriEncoder;

import java.util.Date;
import java.util.Map;

@Service("cosService")
public class CosServiceImpl implements ICosService {
	
	private static final Logger logger = LogManager.getLogger(CosServiceImpl.class);
	
	@Autowired
    private IUploadService uploadService;
	
	@Autowired
    private CmqService cmqService;
	
	@Autowired
    private AttachFileMapper attachFileDAO;
    
    @Autowired
    private TransformJobMapper transformJobDAO;

	
	public Map<String, Object> initiateMultipartUpload(AttachFile attach) throws Exception {
		String cosKey = CosUtil.getCosKey(attach.getFileName(), attach.getUserId(), attach.getPlatformCode());
		attach.setFilePath(cosKey);;
		return CosUtil.initiateMultipartUpload(attach);
	}

	public String getPartCosAuthorization(JSONObject object) throws Exception {
		String cosKey = object.optString("cosKey");
		Map<String, String> params = object.optJSONObject("parameters");
    	Map<String, String> headers = object.optJSONObject("headers");
//		return CosUtil.apiAuth(cosKey,params, headers );
		return CosUtil.getAuthorization(cosKey, headers, params);
	}
	
	public Map<String, Object> getSimpleCosAuthorization(AttachFile attach) throws Exception {
		Map<String, Object> map = MapUtil.newHashMap();
		String cosKey = CosUtil.getCosKey(attach.getFileName(), attach.getUserId(), attach.getPlatformCode());
		String authorization = CosUtil.getAuthorization(cosKey, null, null);
		map.put("cosKey", cosKey);
		map.put("authorization", authorization);
		map.put("host", MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint"));
		return map;
	}

	public Map<String, Object> completeMultipartUpload(AttachFile attach) throws Exception {
		Map<String, Object> map = MapUtil.newHashMap();
		String cosKey = attach.getFilePath();
		String uploadId = attach.getUploadId();
		CosUtil.CompleteMultipartUploadResult(cosKey,uploadId,attach.getApplyType());
		attach = uploadService.finishUploadFile(attach);
		map.put("fid", String.valueOf(attach.getFid()));
		String downloadUrl = "";
		String bucketName = MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET);
		if("0".equals(MemcacheUtil.getDatabaseObj(bucketName))) {
			downloadUrl = CosUtil.getAuthDownloadUrlForPrivate(attach.getFilePath(),attach.getApplyType());
		}else {
			downloadUrl = CosUtil.getAuthDownloadUrl(attach.getFilePath(),attach.getApplyType());
		}
		String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
		String customSourceUrl = (String)MemcacheUtil.getObj(attach.getApplyType()+"-customSourceBucket");
		if(StringUtils.isNotBlank(customSourceUrl)){
			downloadUrl = downloadUrl.replace(downloadUrl.substring(0,downloadUrl.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
		}
		map.put("downloadUrl", downloadUrl);
		map.put("fileLength", attach.getFileLength());
		return map;
	}
	
	public Map<String, Object> finishUploadFile(AttachFile attach) throws Exception {
		Map<String, Object> map = MapUtil.newHashMap();
		Long start = System.currentTimeMillis();
		attach = uploadService.finishUploadFile(attach);
		Long end = System.currentTimeMillis();
		logger.info("插入附件到es中的数据时间：Run Time: " + (end - start) + "(ms)");
		map.put("fid", String.valueOf(attach.getFid()));
		String bucketName = MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET);
		String previewUrl = "";
		String downloadUrl = "";
		if("0".equals(MemcacheUtil.getDatabaseObj(bucketName))) {
			downloadUrl = CosUtil.getAuthDownloadUrlForPrivate(attach.getFilePath(),attach.getApplyType());
			if(Consts.picList.contains(attach.getFileExt().toLowerCase())) {
				previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(attach.getFilePath()), attach.getApplyType());
			}else if(Consts.docList.contains(attach.getFileExt().toLowerCase())){
				//人人通pdf文件不走直接用文件路径在浏览器预览
				/*if("pdf".equals(attach.getFileExt().toLowerCase())&&"3d3080afd6194d5cabef845ebff66829".equals(attach.getApplyType())){
					previewUrl = "http://"+MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint")+CosUtil.getCorrectKey(attach.getFilePath());
				}else*/
					if("linux".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrl(String.valueOf(attach.getFid()));
				}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrlV4(String.valueOf(attach.getFid()),attach.getFileExt().toLowerCase());
				}else if("cos".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
					previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(attach.getFilePath()), attach.getApplyType())+"&ci-process=doc-preview&dstType=html";
				}else{
					previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+attach.getFid();
				}
    		}else if("tir".equals(attach.getFileExt().toLowerCase())&&"3d3080afd6194d5cabef845ebff66829".equals(attach.getApplyType())){
				String tirPath = "tir/"+attach.getFileName().substring(0,attach.getFileName().lastIndexOf("."))+"/index.html";
				previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(tirPath), "422b9062447b400f865d379373d4d6c6");
			}
		}else {
			downloadUrl = CosUtil.getAuthDownloadUrl(attach.getFilePath(),attach.getApplyType());
			if(Consts.picList.contains(attach.getFileExt().toLowerCase())) {
    			previewUrl = "http://"+MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint")+CosUtil.getCorrectKey(UriEncoder.encode(attach.getFilePath()));
			}else if(Consts.docList.contains(attach.getFileExt().toLowerCase())){
				if("linux".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrl(String.valueOf(attach.getFid()));
				}else if("wps-4".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
					previewUrl = WPSUtil.getpreviewUrlV4(String.valueOf(attach.getFid()),attach.getFileExt().toLowerCase());
				}else if("cos".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
					previewUrl = CosUtil.getAuthPicPreviewUrl(CosUtil.getCorrectKey(attach.getFilePath()), attach.getApplyType())+"&ci-process=doc-preview&dstType=html";
				}else{
					previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+"?fid="+attach.getFid();
				}
    		}
		}
		if(StringUtils.isNotBlank(previewUrl)) {
			previewUrl = previewUrl.replace(MemcacheUtil.getDatabaseObj("cos-endpoint"), MemcacheUtil.getDatabaseObj("cos-cdn-endpoint"));
		}
		String cdnUrl = MemcacheUtil.getDatabaseObj("cos-cdn-endpoint");
		String customDestUrl = (String)MemcacheUtil.getObj(attach.getApplyType()+"-customDestBucket");
		String customSourceUrl = (String)MemcacheUtil.getObj(attach.getApplyType()+"-customSourceBucket");
		if(StringUtils.isNotBlank(customSourceUrl)){
			downloadUrl = downloadUrl.replace(downloadUrl.substring(0,downloadUrl.indexOf(cdnUrl)+cdnUrl.length()),customSourceUrl);
		}
		//自定义域名不为空的话，修改预览地址和下载为自定义域名，图片和视频预览地址的桶名不一样
		//上传音视频文件，需要转码完成后才能拿到预览地址
		/*if(Consts.audioList.contains(attach.getFileExt().toLowerCase())||Consts.videoList.contains(attach.getFileExt().toLowerCase())) {
			if (StringUtils.isNotBlank(customDestUrl)) {
				previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customDestUrl);
			}
		}else */
		if(Consts.picList.contains(attach.getFileExt().toLowerCase())||Consts.movieList.contains(attach.getFileExt().toLowerCase())||"mp3".equals(attach.getFileExt().toLowerCase())) {
			if (StringUtils.isNotBlank(customSourceUrl)&&StringUtils.isNotBlank(previewUrl)) {
				previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
			}
		}else if(Consts.docList.contains(attach.getFileExt().toLowerCase())&&"office365".equals(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-previewVersion"))){
			previewUrl = MemcacheUtil.getDatabaseObj("officePrefix")+DESEncrypt.encode(downloadUrl);
		}
		/*else if ("pdf".equals(attach.getFileExt()) && "3d3080afd6194d5cabef845ebff66829".equals(attach.getApplyType())) {
			if (StringUtils.isNotBlank(customSourceUrl) && StringUtils.isNotBlank(previewUrl)) {
				previewUrl = previewUrl.replace(previewUrl.substring(0, previewUrl.indexOf(cdnUrl) + cdnUrl.length()), customSourceUrl);
			}
		}*/
		map.put("downloadUrl", downloadUrl);
		map.put("previewUrl",previewUrl);
		map.put("fileLength", attach.getFileLength());
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		EsAttachment es = new EsAttachment(attach);
		es.setBucketName(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET));
		es.setPreviewUrl(previewUrl);
		es.setDownloadUrl(downloadUrl);
		JSONObject esObj = JSONObject.fromObject(es,jsonConfig);
		MemcacheUtil.putObj(String.valueOf(attach.getFid()), esObj.toString(), 60);
		return map;
	}
	
	public void handVTS(final AttachFile attach) throws Exception {
		ThreadPoolUtil.execute(new Runnable() {
			public void run() {
				try {
					String fileExt = attach.getFileExt();
					logger.info("文件路径=========》"+attach.getFilePath()+"======文件fid===="+attach.getFid());
					if(Consts.videoList.contains(fileExt.toLowerCase())) {
						handVTSMedia(attach,1);
					}else if(Consts.audioList.contains(fileExt.toLowerCase())) {
						handVTSMedia(attach,2);
					}else if(Consts.picList.contains(fileExt.toLowerCase())||Consts.docList.contains(fileExt.toLowerCase())) {
						saveOtherInfo(attach,1);
					}else {
						saveOtherInfo(attach,2);
					}
				} catch (Exception e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
			}
		});
	}
	
	public String transformForFid(JSONObject json) {
		/*ThreadPoolUtil.execute(new Runnable() {
			public void run() {*/
				String transformId = "";
				try {
					String fileExt = json.optString("fileExt");
					if(Consts.videoList.contains(fileExt.toLowerCase())) {
						transformId = transformMedia(json,1);
					}else if(Consts.audioList.contains(fileExt.toLowerCase())) {
						transformId = transformMedia(json,2);
					}
				} catch (Exception e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
				return transformId;
			/*}
		});*/
	}

	@Override
	public JSONObject getTransformInfoForV5(String fid, cn.hutool.json.JSONObject data) throws Exception {
		String previewUrl = "";
		Long duration = 0l;
		String thumbnailUrl = "";
		Long transFileLength = 0l;
		boolean flag = true;
		String status = data.getStr("Status");
		int code = data.getInt("ErrCode");
		String taskId = data.getStr("TaskId");
		if("FINISH".equals(status)&&code==0) {
			cn.hutool.json.JSONArray jsonArr = data.getJSONArray("MediaProcessResultSet");
			for(int i=0;i<jsonArr.size();i++) {
				cn.hutool.json.JSONObject obj = jsonArr.getJSONObject(i);
				String Type = obj.getStr("Type");
				if("Transcode".equals(Type)) {   //转码视频信息
					cn.hutool.json.JSONObject TranscodeTask = obj.getJSONObject("TranscodeTask");
					String TranscodeTaskStatus = TranscodeTask.getStr("Status");
					if("SUCCESS".equals(TranscodeTaskStatus)) {
						cn.hutool.json.JSONObject Output = TranscodeTask.getJSONObject("Output");
						previewUrl = Output.getStr("Path");
						duration = Output.getLong("Duration");
						transFileLength = Output.getLong("Size");
					}else {
						flag = false;  //转码失败
					}
				}
				if("SnapshotByTimeOffset".equals(Type)) {
					cn.hutool.json.JSONObject SnapshotByTimeOffsetTask = obj.getJSONObject("SnapshotByTimeOffsetTask");
					String SnapshotByTimeOffsetTaskStatus = SnapshotByTimeOffsetTask.getStr("Status");
					if("SUCCESS".equals(SnapshotByTimeOffsetTaskStatus)) {
						cn.hutool.json.JSONObject Output = SnapshotByTimeOffsetTask.getJSONObject("Output");
						cn.hutool.json.JSONArray PicInfoSet = Output.getJSONArray("PicInfoSet");
						if(PicInfoSet.size()>0) {
							thumbnailUrl = PicInfoSet.getJSONObject(0).getStr("Path");
						}
					}
				}
			}
		} else {
			flag = false;
		}
		JSONObject es = EsUtil.searchDoc(fid);
		if(null != es) {
			String applyType = es.optString("applyType");
			String endpoint = "http://"+MemcacheUtil.getDatabaseObj(applyType+"-"+Consts.DEST_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint");
			if(flag) {
				es.put("transformStutas", "1");
				es.put("previewUrl", endpoint+previewUrl);
				es.put("transFileLength", transFileLength);
				es.put("duration", duration);
				es.put("thumbnailUrl", endpoint+thumbnailUrl);
			}else {
				es.put("transformStutas", "2");  //转码失败
			}
			EsUtil.addOrUpdateDoc(fid, es.toString());
			return es;
		} else {
			return null;
		}
		/*SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
		boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("transformId",taskId));
		sourceBuilder.query(boolQueryBuilder);
		JSONObject esJson = EsUtil.criteriaQuery(sourceBuilder);
		if(esJson.getInt("count") > 0) {
			JSONArray esList = esJson.optJSONArray("data");
			for(int i = 0;i < esList.size(); i++) {
				JSONObject es = esList.optJSONObject(i);
				String applyType = es.optString("applyType");
				String endpoint = "http://"+MemcacheUtil.getDatabaseObj(applyType+"-"+Consts.DEST_BUCKET)+"."+MemcacheUtil.getDatabaseObj("cos-endpoint");
				if(flag) {
					es.put("transformStutas", "1");
					es.put("previewUrl", endpoint+previewUrl);
					es.put("transFileLength", transFileLength);
					es.put("duration", duration);
					es.put("thumbnailUrl", endpoint+thumbnailUrl);
				}else {
					es.put("transformStutas", "2");  //转码失败
				}
				EsUtil.addOrUpdateDoc(es.getString("fid"), es.toString());
			}
			return esList.getJSONObject(0);
		} else {
			return null;
		}*/
	}

	public String transformMedia(JSONObject json, int type) {
		try {
			//String transformId = CosUtil.ProcessCosMedia(json.optString("filePath"),type,json.optString("applyType"),json.optString("fid"));
			//新版触发转码接口
			String transformId = CosUtil.ProcessMedia(json.optString("filePath"),type,json.optString("applyType"),json.optString("fid"));
			logger.info("调用转码完成，转码id为============="+transformId);
			json.put("transformId", transformId);
			json.put("thumbnailId", transformId);
			EsUtil.addOrUpdateDoc(json.optString("fid"), json.toString());
			return transformId;
		}catch(Exception e) {
			logger.error("调用转码报错========"+e.getMessage());
			return null;
		}
	}
	
	public void handVTSMedia(AttachFile attach,int type) throws Exception {
		try {
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
			String transformId = "";
			if("1".equals(attach.getNeedTransform())) {
				try {
					//transformId = CosUtil.ProcessCosMedia(attach.getFilePath(),type,attach.getApplyType(),attach.getFid().toString());
					//新版触发转码接口
					transformId = CosUtil.ProcessMedia(attach.getFilePath(),type,attach.getApplyType(),attach.getFid().toString());
					logger.info("调用转码完成，转码id为============="+transformId);
					attach.setTransformId(transformId);
					attach.setThumbnailId(transformId);
				}catch(Exception e) {
					logger.error("调用转码报错========"+e.getMessage());
				}
			}
			EsAttachment es = new EsAttachment(attach);
			es.setBucketName(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET));
			String downloadUrl = CosUtil.getAuthDownloadUrl(attach.getFilePath(),attach.getApplyType());
			es.setDownloadUrl(downloadUrl);
			if("1".equals(attach.getNeedTransform())) {
				es.setTransformStutas("0"); //转码中
			}
			logger.info("调用转码完成，相关文件信息为============="+JSONObject.fromObject(attach).toString());
			JSONObject tableAtt = JSONObject.fromObject(attach,jsonConfig);
			tableAtt.put(Consts.TABLE_TYPE, Consts.TABLE_ATTACHMENT);
			//String messageId = cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), tableAtt.toString());
			//logger.info("插入CMQ完成,messageId====="+messageId+"，相关文件信息为============="+JSONObject.fromObject(attach).toString());
			JSONObject esObj = JSONObject.fromObject(es,jsonConfig);
			EsUtil.addOrUpdateDoc(String.valueOf(attach.getFid()), esObj.toString());
			logger.info("更新ES完成，相关文件信息为============="+JSONObject.fromObject(attach).toString());
			if("1".equals(attach.getNeedTransform())) {
				TransformJob job = saveCosJob(es);
				JSONObject tableJob = JSONObject.fromObject(job);
				tableJob.put(Consts.TABLE_TYPE, Consts.TABLE_TRANSFORM);
				String jobMessageId = cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), tableJob.toString());
				logger.info("插入CMQ完成,jobMessageId====="+jobMessageId+"，相关文件信息为============="+JSONObject.fromObject(job).toString());
			}
			//修改触发cmq转码在最后执行
			String messageId = cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), tableAtt.toString());
			logger.info("插入CMQ完成,messageId====="+messageId+"，相关文件信息为============="+JSONObject.fromObject(attach).toString());
//			attachFileDAO.insert(attach);
//			transformJobDAO.insert(job);
		} catch (Exception e) {
			logger.error("抛出异常{}，fid:{}",e.getMessage(),attach.getFid());
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	/*public void handVTSaudio(AttachFile attach) throws Exception{
		String transformId = CosUtil.ProcessCosMedia(attach.getFilePath(),2);
		attach.setTransformId(transformId);
		attach.setThumbnailId(transformId);
		EsAttachment es = new EsAttachment(attach);
		es.setBucketName(MemcacheUtil.getDatabaseObj("cos-sourceBucketName"));
		String downloadUrl = CosUtil.getDownloadUrl(attach.getFilePath());
		es.setDownloadUrl(downloadUrl);
		es.setTransformStutas("0"); //转码中
		JSONObject esObj = JSONObject.fromObject(es);
		EsUtil.addOrUpdateDoc(String.valueOf(attach.getFid()), esObj.toString());
		TransformJob job = saveCosJob(es);
		try {
			cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), JSONObject.fromObject(attach).toString());
			cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), JSONObject.fromObject(job).toString());
//			attachFileDAO.insert(attach);
//			transformJobDAO.insert(job);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}*/
	
	public void savePicInfo(AttachFile attach,int type) throws Exception {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		
		EsAttachment es = new EsAttachment(attach);
		es.setBucketName(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET));
		String previewUrl = "";
		if(type==1) {
			previewUrl = MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+ "?fid=" + attach.getFid();
//			previewUrl = WPSUtil.getpreviewUrl(String.valueOf(attach.getFid()));
		}	
		String downloadUrl = CosUtil.getAuthDownloadUrl(attach.getFilePath(),attach.getApplyType());
		es.setDownloadUrl(downloadUrl);
		es.setPreviewUrl(previewUrl);
		JSONObject esObj = JSONObject.fromObject(es,jsonConfig);
		EsUtil.addOrUpdateDoc(String.valueOf(attach.getFid()), esObj.toString());
		JSONObject tableAtt = JSONObject.fromObject(attach,jsonConfig);
		tableAtt.put(Consts.TABLE_TYPE, Consts.TABLE_ATTACHMENT);
		try {
			cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), tableAtt.toString());
//			attachFileDAO.insert(attach);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void saveOtherInfo(AttachFile attach,int type) throws Exception {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		
		EsAttachment es = new EsAttachment(attach);
		es.setBucketName(MemcacheUtil.getDatabaseObj(attach.getApplyType()+"-"+Consts.SOURCE_BUCKET));
		String downloadUrl = CosUtil.getAuthDownloadUrl(attach.getFilePath(),attach.getApplyType());
		es.setDownloadUrl(downloadUrl);
		if(type==1) {
//			es.setPreviewUrl(WPSUtil.getpreviewUrl(String.valueOf(attach.getFid())));
			es.setPreviewUrl(MemcacheUtil.getDatabaseObj(Consts.WPS_UL_KEY)+ "?fid=" + attach.getFid());

		}
		JSONObject esObj = JSONObject.fromObject(es,jsonConfig);
		EsUtil.addOrUpdateDoc(String.valueOf(attach.getFid()), esObj.toString());
		JSONObject tableAtt = JSONObject.fromObject(attach,jsonConfig);
		tableAtt.put(Consts.TABLE_TYPE, Consts.TABLE_ATTACHMENT);
		try {
			cmqService.sendMsg(MemcacheUtil.getDatabaseObj(Consts.CMQ_ATTACHMENT_QUEUE), tableAtt.toString());
//			attachFileDAO.insert(attach);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public JSONObject getTransformInfo(JSONObject data) throws Exception {
		String previewUrl = "";
		Long duration = 0l;
		String thumbnailUrl = "";
		Long transFileLength = 0l;
		JSONArray processTaskList =  data.optJSONArray("processTaskList");
		String vodTaskId = data.optString("vodTaskId");
		if(null!=processTaskList&&processTaskList.size()>0) {
			for(int i = 0;i<processTaskList.size();i++) {
				JSONObject json = processTaskList.optJSONObject(i);
				String taskType = json.optString("taskType");
				String status = json.optString("status");
				if("Transcode".equals(taskType)&&"SUCCESS".equals(status)) {
					JSONObject output = json.optJSONObject("output");
					previewUrl = output.optString("url");
					duration = output.optLong("duration");
					transFileLength = output.optLong("size");
				}else if("SnapshotByTimeOffset".equals(taskType)&&"SUCCESS".equals(status)) {
					JSONObject output = json.optJSONObject("output");
					JSONArray imgInfo = output.optJSONArray("imgInfo");
					if(null!=imgInfo && imgInfo.size()>0) {
						thumbnailUrl = imgInfo.optJSONObject(0).optString("url");
					}
				}
			}
		}
		
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("transformId",vodTaskId));
    	sourceBuilder.query(boolQueryBuilder);
    	JSONObject esJson = EsUtil.criteriaQuery(sourceBuilder);
    	JSONArray esList = esJson.optJSONArray("data");
    	for(int i=0;i<esList.size();i++) {
    		JSONObject es = esList.optJSONObject(i);
    		String fid = String.valueOf(es.optLong("fid"));
    		es.put("transformStutas", "1");
    		es.put("previewUrl", previewUrl);
    		es.put("transFileLength", transFileLength);
    		es.put("duration", duration);
    		es.put("thumbnailUrl", thumbnailUrl);
    		EsUtil.addOrUpdateDoc(fid, es.toString());
    	}
    	if(esList.size()>0) {
    		return esList.optJSONObject(0); 
    	}else {
    		return null;
    	}
	}
	
	/**
	 * 转码后拉取消息队列后解析转码信息
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public JSONObject getTransformInfoNew(JSONObject data) throws Exception {
		String previewUrl = "";
		Long duration = 0l;
		String thumbnailUrl = "";
		Long transFileLength = 0l;
		String vodTaskId = data.optString("TaskId");
		JSONArray processTaskList =  data.optJSONArray("MediaProcessResultSet");
		if(null!=processTaskList&&processTaskList.size()>0) {
			for(int i = 0;i<processTaskList.size();i++) {
				JSONObject json = processTaskList.optJSONObject(i);
				String taskType = json.optString("Type");
				if("Transcode".equals(taskType)) {
					JSONObject TranscodeTask = json.optJSONObject("TranscodeTask");
					String status = TranscodeTask.optString("Status");
					if("SUCCESS".equals(status)) {
						JSONObject output = TranscodeTask.optJSONObject("Output");
						previewUrl = output.optString("Url");
						duration = output.optLong("Duration");
						transFileLength = output.optLong("Size");
					}
				}else if("SnapshotByTimeOffset".equals(taskType)) {
					JSONObject SnapshotByTimeOffsetTask = json.optJSONObject("SnapshotByTimeOffsetTask");
					String status = SnapshotByTimeOffsetTask.optString("Status");
					if("SUCCESS".equals(status)) {
						JSONObject output = SnapshotByTimeOffsetTask.optJSONObject("Output");
						JSONArray PicInfoSet = output.optJSONArray("PicInfoSet");
						if(null!=PicInfoSet && PicInfoSet.size()>0) {
							thumbnailUrl = PicInfoSet.optJSONObject(0).optString("Url");
						}
					}
				}
			}
		}
		
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("transformId",vodTaskId));
    	sourceBuilder.query(boolQueryBuilder);
    	JSONObject esJson = EsUtil.criteriaQuery(sourceBuilder);
    	JSONArray esList = esJson.optJSONArray("data");
    	for(int i=0;i<esList.size();i++) {
    		JSONObject es = esList.optJSONObject(i);
    		String fid = String.valueOf(es.optLong("fid"));
    		es.put("transformStutas", "1");
    		es.put("previewUrl", previewUrl);
    		es.put("transFileLength", transFileLength);
    		es.put("duration", duration);
    		es.put("thumbnailUrl", thumbnailUrl);
    		EsUtil.addOrUpdateDoc(fid, es.toString());
    	}
    	if(esList.size()>0) {
    		return esList.optJSONObject(0); 
    	}else {
    		return null;
    	}
	}
	
	public TransformJob saveCosJob(EsAttachment es) throws Exception {
		TransformJob job = new TransformJob();
		job.setTransformId(es.getTransformId());
		job.setTransformType("3");  //腾讯云的转码和缩略图是一个任务
		job.setBucketName(MemcacheUtil.getDatabaseObj(es.getApplyType()+"-"+Consts.DEST_BUCKET));
		job.setTransformStatus("0");  //转码中
		return job;
	}

	@Override
	public Map<String, String> getTempCredential(String buketName, String region) {
		return CosUtil.getSts(buketName, region);
	}


}
